package cn.yechen.yygh.hosp.service.impl;

import cn.yechen.yygh.hosp.repository.DepartmentRepository;
import cn.yechen.yygh.hosp.service.DepartmentService;
import cn.yechen.yygh.model.hosp.Department;
import cn.yechen.yygh.vo.hosp.DepartmentQueryVo;
import cn.yechen.yygh.vo.hosp.DepartmentVo;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author yechen
 * @create 2021-08-17 16:31
 */
@Service
public class DepartmentServiceImpl implements DepartmentService {
    @Autowired
    private DepartmentRepository departmentRepository;

    @Override
    public void saveDepartment(Map<String, Object> parameterMap) {
        // 将 map 转为 Department 对象
        String jsonString = JSONObject.toJSONString(parameterMap);
        Department department = JSONObject.parseObject(jsonString, Department.class);
        // 通过医院编号和部门编号查询
        Department departmentExit = departmentRepository.getDepartmentByHoscodeAndDepcode(department.getHoscode(), department.getDepcode());

        if (departmentExit == null) {
            // 不存在，添加操作
            department.setCreateTime(new Date());
        } else {
            // 存在，更新操作
            department.setId(departmentExit.getId());
            department.setCreateTime(departmentExit.getCreateTime());
            department.setUpdateTime(new Date());
        }
        department.setIsDeleted(0);

        // 保存
        departmentRepository.save(department);
    }

    @Override
    public Page<Department> findPageDepartment(int page, int limit, String hoscode) {
        // 查询参数
        ExampleMatcher exampleMatcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase();
        Department department = new Department();
        department.setHoscode(hoscode);
        department.setIsDeleted(0);
        Example<Department> example = Example.of(department, exampleMatcher);

        // 分页
        Pageable pageable = PageRequest.of(page-1, limit);

        // 查询
        Page<Department> all = departmentRepository.findAll(example, pageable);

        return all;
    }

    @Override
    public void removeDepartment(String hoscode, String depcode) {
        // 通过 hoscode 和 depcode 查询部门是否存在
        Department department = departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);
        // 如果存在，通过 id 删除
        if (department != null) {
            departmentRepository.deleteById(department.getId());
        }
    }

    @Override
    public List<DepartmentVo> getDepList(String hoscode) {
        // 创建 List 集合，用于最后数据的封装
        List<DepartmentVo> resultList = new ArrayList<>();

        // 根据医院编号查询所有科室信息
        Department departmentQuery = new Department();
        departmentQuery.setHoscode(hoscode);
        Example<Department> example = Example.of(departmentQuery);
        List<Department> allDepartmentList = departmentRepository.findAll(example);

        // 根据大科室编号（bigcode）进行分组，获取每个大科室里面的下级子科室（灵幻语句）
        Map<String, List<Department>> departmentMap = allDepartmentList.stream().collect(Collectors.groupingBy(Department::getBigcode));

        // 编历 map 集合
        for (Map.Entry<String, List<Department>> entry : departmentMap.entrySet()) {
            // 大科室编号
            String bigCode = entry.getKey();
            // 对应大科室下所有的科室列表
            List<Department> departmentList = entry.getValue();

            // 封装小科室列表
            List<DepartmentVo> childrenDepartmentVoList = new ArrayList<>();
            for (Department department : departmentList) {
                DepartmentVo childrenDepartmentVo = new DepartmentVo();
                childrenDepartmentVo.setDepcode(department.getDepcode());
                childrenDepartmentVo.setDepname(department.getDepname());
                // 加入到小科室列表
                childrenDepartmentVoList.add(childrenDepartmentVo);
            }

            // 封装大科室
            DepartmentVo parentDepartmentVo = new DepartmentVo();
            parentDepartmentVo.setDepcode(bigCode);
            parentDepartmentVo.setDepname(departmentList.get(0).getBigname());
            parentDepartmentVo.setChildren(childrenDepartmentVoList);

            // 将大科室放入结果结合
            resultList.add(parentDepartmentVo);
        }
        return resultList;
    }
}
